package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.common.BaseServiceImpl;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.MaterialService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
@Log4j2
public class WmMaterialServiceImpl extends BaseServiceImpl<WmMaterialMapper, WmMaterial> implements MaterialService {

    @Autowired
    private FastDFSClient fastDFSClient;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Value("${fdfs.url}")
    private String fileServerUrl;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.检查参数
        if (multipartFile == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.上传图片到fasfdfs
        String fileId = null;
        try {
            fileId = fastDFSClient.uploadFile(multipartFile);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

        //3.保存素材数据到表中 wm_material
        Integer user = WmThreadLocalUtils.getUserId();
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setUserId(user);
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);
        //拼接图片路径
        wmMaterial.setUrl(fileServerUrl + fileId);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        if (dto == null)return errorResult;
        Integer userId = WmThreadLocalUtils.getUserId();
        if (userId == null)return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户Id不存在");
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmMaterial::getId,userId);
        if (dto.getIsCollection() !=null && dto.getIsCollection() == 1){
            wrapper.eq(WmMaterial::getIsCollection,1);
        }
        //按照日期倒序排序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        Page<WmMaterial> page = new Page<>(dto.page, dto.size);
        IPage<WmMaterial> pageResult = page(page, wrapper);
        ResponseResult result = new PageResponseResult(dto.page, dto.size, (int) pageResult.getTotal());
        List<WmMaterial> backList = pageResult.getRecords();
        for (WmMaterial wmMaterial : backList) {
            wmMaterial.setUrl(fileServerUrl + wmMaterial.getUrl());
        }
//        backList.stream().map(wmMaterial -> {
//            wmMaterial.setUrl(fileServerUrl + wmMaterial.getUrl());
//            return wmMaterial;
//        }).collect(Collectors.toList());
        result.setData(backList);
        return result;
    }

    @Override
    public ResponseResult delPicture(Integer id) {
        LambdaQueryWrapper<WmNewsMaterial> eq = Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id);
        Integer count = wmNewsMaterialMapper.selectCount(eq);
        if (count>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"该资源被引用，不能删除");
        }
        WmMaterial byId = getById(id);
        String url = byId.getUrl();
        fastDFSClient.delFile(url);
        removeById(id);
        return sucResult;
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        if (id == null)return errorResult;
        update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection,type).eq(WmMaterial::getId,id));
        return sucResult;
    }
}
